home *** CD-ROM | disk | FTP | other *** search
- Path: radmail.rad.co.il!usenet
- From: udi <udi@radnet.co.il>
- Newsgroups: comp.lang.c++
- Subject: Deleting Data Members that are Const Pointers / References?
- Date: 26 Feb 1996 07:50:31 GMT
- Organization: radnet.co.il
- Message-ID: <4groo7$4bt@radmail.rad.co.il>
- NNTP-Posting-Host: gate.radnet.co.il
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.2N (Windows; I; 16bit)
-
- news:comp.lang.c++#pvcybpuqx6p.fsf@hln56.pki-nbg.philips.de
-
- Hi everybody,
-
- I have a simple question regarding data members that are
- constant pointers or references.
- Let's say I have a class Foo that has a data member xr (say of type int&
- - in reality a different type) that is a constant reference. Objects of
- class Foo must have an instance of xr during their lifetime, that's a
- reason to have xr a reference. Also, xr must not change (not even
- accidentaly, by some member function / friend of Foo), that's why I want
- xr to be constant.Foo is always initialized with an int that was
- allocated off the heap, but xr should cease to exist when Foo does, so
- Foo is responsible to destroy xr and free the memory occupied by it.
- However, deleting a const reference (pointer) is not allowed (at least
- according to Borland 4.5 and g++). This seems logical as the operand to
- delete is a void* and the compiler says he can't convert a const int* to
- a void*.
- So, THE QUESTION IS:
- Is there an alternative to brutally casting the const away?
-
- A sample code:
-
- class Foo [
- public:
- Foo(const int& xr1) : xr(xr1) {}
- ~Foo() [ delete &xr; ] // ERROR - attempt to delete a constant pointer
- private:
- int& xr;
- ];
-
- int main() {
- int& xr1 = *(new int(100));
- Foo* fooP = new Foo(xr1);
- //...
- delete fooP;
- }
-
- Alternative:
- ~Foo() [ delete (int*)(&xr); ] // BRUTAL CASTING
-
- --
- Udi Ron
- RADNET
-
- Tel: +972-3-6459585
- Fax: +972-3-6480582
- E-Mail: udi@gate.radnet.co.il
-
-
-